﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.Entity;
using JustMVCTest.Models;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Data.Entity.Validation;


//IMPORTANT: status 67: ask to decrease amouunt status 66: ask to increase percent status 2:ask to edit delivery date status 1: ask to close
namespace JustMVCTest.Controllers
{
    public class POsEditController : Controller
    {
        public void SendPendingMail(Papi_Users Mailto, string Message)
        {
            var client = new SmtpClient("smtp.gmail.com", 587)
            {
                Credentials = new NetworkCredential("papiproj@gmail.com", "0545357710"),
                EnableSsl = true
            };
            var UserMail = Mailto.email;
            client.Send("papiproj@gmail.com", UserMail, " Message from POMP System ", "Hello " + Mailto.domain_username + Message); // " Message from POMP System ", "Hello" + Mailto.domain_username + " , \n A request to postpone the delivery date of PO number: " + new_po.PONumber.ToString() + " to the date: " + new_po.DeliveryDate_Req.ToString() + " has been made. \n Thank you, \n POMP System ");
            Console.WriteLine("Sent");
            Console.ReadLine();
        }

        private PODBContext db2 = new PODBContext();
        //
        // GET: /POsList/

        public ActionResult Edit(int Item, long PONumber)
        {
            var pos = from m in db2.POs
                      select m;
            if (pos == null)
            {
                return HttpNotFound();
            }

            pos = pos.Where(s => s.latest == 1);
            pos = pos.Where(s => s.Item == Item);
            pos = pos.Where(s => s.PONumber == PONumber);

            int last = pos.First().Update_Num;
            PO po = db2.POs.Find(PONumber, Item, last);
            if (po == null)
            {
                return HttpNotFound();
            }
            return View(po);
        }


        [HttpPost]
        public ActionResult Edit(PO po)
        {

            var client = new SmtpClient("smtp.gmail.com", 587)
            {
                Credentials = new NetworkCredential("papiproj@gmail.com", "0545357710"),
                EnableSsl = true
            };
            // if (ModelState.IsValid)
            //{
            // db2.Entry(po).State = EntityState.Modified;
            //db2.SaveChanges(); 

            var pos = from m in db2.POs
                      select m;

            pos = pos.Where(s => s.latest == 1);
            pos = pos.Where(s => s.Item == po.Item);
            pos = pos.Where(s => s.PONumber == po.PONumber);
            if (pos == null)
            {
                return HttpNotFound();
            }

            pos.First().latest = 0;
            int curr_version = pos.First().Update_Num;
            //db2.SaveChanges();


            PO new_po = new PO { };
            //new_po = pos.First();


            new_po.co_el_name = pos.First().co_el_name;
            new_po.Cost_Cent = pos.First().Cost_Cent;
            new_po.cost_elem = pos.First().cost_elem;
            new_po.DeliveryDate = pos.First().DeliveryDate;
            new_po.DeliveryDate_Req = pos.First().DeliveryDate_Req;
            new_po.Descr = pos.First().Descr;
            new_po.Int_Order = pos.First().Int_Order;
            new_po.Item = pos.First().Item;
            new_po.latest = 1;
            new_po.Open_Amt_L = pos.First().Open_Amt_L;
            new_po.Open_Amt_T = pos.First().Open_Amt_T;
            new_po.Open_Qty = pos.First().Open_Qty;
            new_po.Ord_Qty = pos.First().Ord_Qty;
            new_po.Order_Amt = pos.First().Order_Amt;
            new_po.Percentage = pos.First().Percentage;
            new_po.PONumber = pos.First().PONumber;
            new_po.Prof_Cent = pos.First().Prof_Cent;
            new_po.Requisitioner = pos.First().Requisitioner;
            new_po.Sch_Lin = pos.First().Sch_Lin;
            new_po.Status = 2;
            new_po.T_Curr = pos.First().T_Curr;
            new_po.UM = pos.First().UM;
            new_po.Update_Date = pos.First().Update_Date;
            new_po.Update_Num = pos.First().Update_Num;
            new_po.Vendor = pos.First().Vendor;
            new_po.VendorName = pos.First().VendorName;
            new_po.TSSC_Pending_Send_Date = pos.First().TSSC_Pending_Send_Date;
            new_po.Purchase_O = pos.First().Purchase_O;
            new_po.DeliveryDate_Req = pos.First().DeliveryDate_Req;
            if (po.Status == 2)
            {
                new_po.DeliveryDate_Req = po.DeliveryDate_Req;
            }

            if ((po.Status == 2) || (po.Status == 1)) // a request to postpone the delivery date
            {
                string sendMessage;
                if (po.Status == 2)
                    sendMessage = " , \n A request to postpone the delivery date of PO number: " + new_po.PONumber.ToString() + " to the date: " + new_po.DeliveryDate_Req.ToString() + " has been made. \n Thank you, \n POMP System ";
                else
                    sendMessage = ", \n A request to close PO number: " + new_po.PONumber.ToString() + " has been made. \n Thank you, \n POMP System ";

                var super_users = from u in db2.Papi_Users_tbl  //send mail to all superusers
                                 where (u.is_superuser == true)
                                 select u;

                if (super_users.Count() > 0)
                {
                    foreach (Papi_Users User in super_users)
                    {
                        SendPendingMail(User, sendMessage);
                    }
                }
                
                
                var int_order = new_po.Int_Order;

                if (!string.IsNullOrEmpty(int_order))
                {
                    var IntOrder = from m in db2.Papi_Users_tbl
                                   select m;
                    IntOrder = IntOrder.Where(s => s.Int_Order == new_po.Int_Order);
                    if (IntOrder.Count() > 0)
                    {
                        foreach (Papi_Users User in IntOrder)
                        {
                            SendPendingMail(User, sendMessage);
                        }
                    }
                }


                var cost_center = new_po.Cost_Cent;

                if (!string.IsNullOrEmpty(cost_center))
                {
                    var CostCenter = from m in db2.Papi_Users_tbl
                                     select m;
                    CostCenter = CostCenter.Where(s => s.Cost_Cent == new_po.Cost_Cent);
                    if (CostCenter.Count() > 0)
                    {
                        foreach (Papi_Users User in CostCenter)
                        {
                            SendPendingMail(User, sendMessage);
                        }
                    }
                }


                var poland = from m in db2.Papi_Users_tbl
                             where (m.is_tssc == true)
                             select m;

                if (poland.Count() > 0)
                {
                    foreach (Papi_Users User in poland)
                    {
                        SendPendingMail(User, sendMessage);
                    }

                }
            }


                new_po.Insert_Date = DateTime.Now;

                if (po.Status == 67)
                {
                    new_po.Open_Amt_L = po.Open_Amt_L;
                }
                else
                {
                    new_po.Open_Amt_L = pos.First().Open_Amt_L;
                }


                if (po.Status == 66)
                {
                    new_po.Percentage = po.Percentage;
                    new_po.Percentage_Update_Date = DateTime.Now;
                }
                else
                {
                    new_po.Percentage = pos.First().Percentage;
                    new_po.Percentage_Update_Date = pos.First().Percentage_Update_Date;
                }



                if ((po.Status == 66) || (po.Status == 67))
                {
                    new_po.Status = pos.First().Status;
                    new_po.TSSC_Pending_Send_Date = pos.First().TSSC_Pending_Send_Date;
                }
                else
                {
                    new_po.Status = po.Status;
                    new_po.TSSC_Pending_Send_Date = DateTime.Now;
                }

                new_po.Update_Date = DateTime.Now;
                new_po.Update_Num = curr_version + 1;



                db2.POs.Add(new_po);

                db2.SaveChanges();

                if ((String)Session["Came_From"] == "ToDo")
                {
                    return RedirectToAction("Index", "ToDoList");
                }

                return RedirectToAction("Index", "POsList");

            }
        }
    }

